<?php

namespace App\Http\Controllers;

use App\Http\Requests\IndexBlindRequest;
use App\Http\Requests\StoreBlindRequest;
use App\Http\Requests\UpdateBlindRequest;
use App\Http\Resources\BlindResource;
use App\Models\Blind;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;

class BlindController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth:sanctum');
    }
    /**
     * Display a listing of the resource.
     */
    public function index(IndexBlindRequest $request)
    {
        $query = Blind::query();
        if (!isSuperadmin()) {
            $query->where('admin_id', auth()->id());
        }
        $query->when($request->filled('name'), function ($query) use ($request) {
            $name = $request->input('name');
            return $query->where(function ($subquery) use ($name) {
                $subquery->where('name', 'like', "%$name%");
            });
        })->when($request->filled('blind_cate_id'), function ($query) use ($request) {
            return $query->where('blind_cate_id', $request->input('blind_cate_id'));
        })->when($request->filled('blind_type'), function ($query) use ($request) {
            return $query->where('blind_type', $request->input('blind_type'));
        })->when($request->filled('type'), function ($query) use ($request) {
            return $query->where('type', $request->input('type'));
        })->when($request->filled('status'), function ($query) use ($request) {
            return $query->where('status', $request->input('status'));
        });

        $data = $query->with(['admins' => function ($query) {
            return $query->select('id', 'username');
        }, 'blindcates' => function ($query) {
            return $query->select('id', 'name');
        }, 'blindshops', 'statuslabel', 'blindtypelabel', 'typelabel'])->orderBy('created_at', 'DESC')->paginate(
            $request->query('pageSize'),
            ['*'],
            'page',
            $request->query('pageNum')
        );
        $response =  BlindResource::collection($data);
        $total = $response->total();
        return $this->success('查询成功', $response, $total);
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(StoreBlindRequest $request, Blind $blind)
    {
        $blind->fill($request->input());
        $blind->admin_id = Auth::id();
        $blind->status = 1;
        $blind->save();

        $shopsData = $request->input('shops');
        foreach ($shopsData as $shop) {
            $blind->blindshops()->attach($shop['shop_id'], ['blind_id' => $blind->id, 'rate' => $shop['rate']]);
        }
        return $this->success('新增盲盒成功', $blind);
    }

    /**
     * Display the specified resource.
     */
    public function show(Blind $blind)
    {
        $this->authorize('view', $blind);
        $data = $blind->load(['admins', 'blindcates', 'blindshops', 'statuslabel', 'blindtypelabel', 'typelabel']);
        return $this->success('查询成功', new BlindResource($data));
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Blind $blind)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(UpdateBlindRequest $request, Blind $blind)
    {
        $this->authorize('update', $blind);
        $blind->fill($request->input());
        $blind->status = 1;
        $blind->admin_id = Auth::id();
        $blind->save();

        $shopsData = $request->input('shops');
        // 使用 sync 方法替换关联数据
        $shopsToSync = [];
        foreach ($shopsData as $shop) {
            $shopsToSync[] = ['blind_id' => $blind->id, 'shop_id' => $shop['shop_id'], 'rate' => $shop['rate']];
        }
        $blind->blindshops()->sync($shopsToSync);
        return $this->success('更新盲盒成功', $blind);
    }

    // public function status(Request $request, $id)
    // {
    //     Validator::make($request->input(), [
    //         'status' => ['required']
    //     ])->validate();
    //     $blind = Blind::findOrFail($id);
    //     $this->authorize('status', $blind);
    //     $blind->status = $request->input('status');
    //     $blind->save();
    //     return $this->success('更新状态成功', $blind);
    // }

    /**
     * 审核接口
     *
     * @param Request $request
     * @param [type] $id
     * @return 
     */
    public function examine(Request $request, $id)
    {
        $blind = Blind::findOrFail($id);
        $this->authorize('status', $blind);
        $blind->status = 3;
        $blind->save();
        return $this->success('更新状态成功', $blind);
    }

    /**
     * 驳回接口
     *
     * @param Request $request
     * @param [type] $id
     * @return 
     */
    public function reject(Request $request, $id)
    {
        $blind = Blind::findOrFail($id);
        $this->authorize('status', $blind);
        $blind->status = 2;
        $blind->save();
        return $this->success('更新状态成功', $blind);
    }


    /**
     * 已上架
     *
     * @param Request $request
     * @param [type] $id
     * @return 
     */
    public function listed(Request $request, $id)
    {
        $blind = Blind::findOrFail($id);
        $this->authorize('status', $blind);
        $blind->status = 5;
        $blind->save();
        return $this->success('更新状态成功', $blind);
    }

    /**
     * 已下架
     *
     * @param Request $request
     * @param [type] $id
     * @return 
     */
    public function delisted(Request $request, $id)
    {
        $blind = Blind::findOrFail($id);
        $this->authorize('status', $blind);
        $blind->status = 4;
        $blind->save();
        return $this->success('更新状态成功', $blind);
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Blind $blind)
    {
        $this->authorize('delete', $blind);
        $blind->delete();
        return $this->success('删除成功', $blind);
    }
}
